package com.nakamachizu.controller.m.mixi;

import java.util.Calendar;
import java.util.Map;
import java.util.logging.Logger;

import org.mobylet.core.Carrier;
import org.mobylet.core.Mobylet;
import org.mobylet.core.MobyletFactory;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;
import org.slim3.util.StringUtil;
import org.slim3.util.TimeZoneLocator;

import com.nakamachizu.meta.mixi.AssociateModelMeta;
import com.nakamachizu.model.mixi.AssociateModel;
import com.nakamachizu.model.mixi.BasePersonFriendModel;
import com.nakamachizu.model.mixi.PersonFriendsModel;
import com.nakamachizu.service.mixi.RestfulService;

public class AssociateController extends Controller {
    
    private static final Logger log = Logger.getLogger(AssociateController.class.getName());
    
    private String cmd;
    private String key;
    private Calendar now;

    @Override
    public Navigation run() throws Exception {
        
        init();
        AssociateModelMeta meta = AssociateModelMeta.get();
        
        if(validate()){
            Mobylet mobylet = MobyletFactory.getInstance();
            Carrier carrier = mobylet.getCarrier();
            if(!carrier.equals(Carrier.OTHER)){
                String guid = mobylet.getGuid();
                if(!StringUtil.isEmpty(guid)){
                    if(StringUtil.isEmpty(cmd)){
                        AssociateModel model = Datastore.query(meta).filter(meta.accessKey.equal(key)).asSingle();
                        if(model != null){
                            if(!StringUtil.isEmpty(model.getGuid()) && !guid.equals(model.getGuid())){
                                log.info("guid changed. before:" + model.getGuid() + " after:" + guid + " mixi id:" + model.getMixiId());
                            }
                            model.setGuid(guid);
                            model.setAssociateDate(now.getTime());
                            RestfulService rfs = new RestfulService();
                            rfs.makeSignature(model.getMixiId(), RestfulService.TARGET_UID_ME, RestfulService.TARGET_TYPE_SELF, RestfulService.FORMAT_JSON, RestfulService.DEFAULT_COUNT, RestfulService.DEFAULT_START_INDEX);
                            if(rfs.request() == 200){
                                PersonFriendsModel pfsm = rfs.getPersonFriendsModel();
                                Map<String,String> map = pfsm.getEntry()[0];
                                model.setDisplayName(map.get(BasePersonFriendModel.DISPLAY_NAME));
                                requestScope("name", model.getDisplayName());
                            }
                            Datastore.put(model);
                        }
                    }else{
                        AssociateModel model = Datastore.query(meta).filter(meta.guid.equal(guid)).asSingle();
                        if(model != null){
                            requestScope("name", model.getDisplayName());
                            Datastore.delete(model.getKey());
                        }else{
                            requestScope("nothing", true);
                        }
                        return forward("/jsp/m/mixi/associate_release.jsp");
                    }
                }
            }
        }
        
        return forward("/jsp/m/mixi/associate.jsp");
    }
    
    private void init(){
        key = requestScope("key");
        cmd = requestScope("cmd");
        now = Calendar.getInstance(TimeZoneLocator.get());

    }
    
    protected boolean validate() {
        boolean result = false;
        Validators v = new Validators(request);
        v.add("key", v.required());
        
        result = v.validate();
        
        return result;
    }
}
